import {
  list
} from '../../api/ingredients'
import {
  _get
} from '../../api/collection_record'
import recipeApi from '../../api/recipe'
import factorApi from '../../api/factor'

import {
  routeAndState,
  numSettingsType
} from '../../dataSource'
import {
  list as fetchListHistory,
  candidate,
  removeById
} from '../../api/performce'



Page({
  options: {
    pureDataPattern: /^__/ // 指定所有 __ 开头的数据字段为纯数据字段
  },
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    dropList: [],
    selectList: [],
    //factorList: [],
    show: false,
    alias: {},
    checkboxValue: [],
    values: [],
    name: '',
    ingredientsList: [],
    id: '',
    dataSource: {},
    numSettingsType,
    // factorSelect: [],
    recordId: null,
    confirmShow: false,
    confirmList: routeAndState,
    pages: getCurrentPages(),
    preData: {},
    status: null,
    enable: true,
    total: 0,
    refreshLoading: false,
    enabledScroll: true,
    root: getApp().globalData.root,
    __historyList: [],
    historyListLength: 0,
    current: 0,
    _performanceData: {
      x: null,
      y: null,
      z: null,
      tRongCorrectionValue: null
    },
    _originData: {},
    enableEdit: true,
    compositionShow: false,
    swipeShow: false
  },

  addPF() {
    const recipeCombination = this.data.values.map((it) => {
      if (it.number && it.number != '0') {
        return {
          number: it.number,
          ingredients: it
        }
      }
    }).filter(it => it)
    if (this.data.selectList.length < 1) {
      wx.showToast({
        title: '没有添加原料',
        icon: 'error'
      })
      return
    }
    const numberSettings = this.selectComponent("#vc-number")?.getDataSource();

    const number_data = numberSettings.map(it => {
      return {
        name: it.name,
        numSelectManageId: it.numSelectManageId,
        remark: it.remark,
        sortNumber: it.sortNumber,
        value: it.value
      }
    })
    const {
      name,
      //  factorSelect

    } = this.data;

    const data = {
      name,
      recipeCombination,
      productionNumberDatas: number_data,
      //  factorManageId: factorSelect[0]
    }
    recipeApi.recipeAdd(data, (e) => {
      wx.showToast({
        title: '完成',
        icon: 'success'
      })
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  onPickerShow() {
    this.setData({
      show: true
    })
  },
  onChange(event) {
    const data = event.detail;
    this.setData({
      checkboxValue: data
    })

  },
  currentChange(event) {
    let c = event.detail.current,
      {
        length
      } = this.data.__historyList,
      {
        current
      } = this.data,
      hl = this.data.historyListLength;

    if (c < length - 1 && c > current && hl < length) {
      hl += 1;
    }

    this.setData({
      current: c,
      historyListLength: hl,
      dataSource: this.data.__historyList[c]
    })
     
    this.recipeHandler(this.data.__historyList[c])
  },
  onSelectConfirm() {
    this.onClose();
    const dropList = [...this.data.dropList];
    let selectList = [...this.data.selectList];
    let checkList = [...this.data.checkboxValue];
    const dl = dropList.filter(it => {
      return !checkList.includes(String(it.value))
    })
    const sl = [...selectList, ...dropList.filter(it => {
      return checkList.includes(String(it.value))
    }).map(it => {
      return {
        ...it,
        number: it.number || '0'
      }
    })]
    this.setData({
      dropList: dl,
      checkboxValue: [],
      selectList: sl
    })
  },
  onCreateHistory(event) {
    const __historyList = this.data.__historyList,
      newData = [...__historyList, event.detail[event.detail.length - 1]];
    this.setData({
      __historyList: newData,
      historyListLength: newData.length
    })
  },
  onLockOn() {
    this.setData({
      enabledScroll: false
    })
  },
  onUnLockOn() {
    this.setData({
      enabledScroll: true
    })
  },
  showPicker() {
    //排序
    this.sortArray();
    this.onPickerShow();
  },
  sortArray() {
    const dropList = [...this.data.dropList];
    if (dropList.length < 1) return
    dropList.sort((a, b) => {
      return String(a.text)[0].localeCompare(String(b.text)[0], 'zh-CN', {
        numeric: true
      })
    })
    this.setData({
      dropList
    })
  },
  xyzChange(event) {
    const key = event.currentTarget.dataset.value;
    this.setData({
      [key]: event.detail
    })
  },
  onFactorClose() {
    this.setData({
      fatorShow: false
    })
  },
  onFactorShow() {
    this.setData({
      fatorShow: true
    })
  },

  onFactorConfirm(event) {
    const obj = event.detail;
    this.setData({
      factorData: obj
    })
    // this.onFactorClose()
  },
  setPage(id, recordId = null) {

    wx.setNavigationBarTitle({
      title: '配方详情'
    })
    this.setData({
      id,
      recordId,
      root: wx.getStorageSync('root')
    })

  },
  /**
   * 查询原料表
   */
  fetchIngredientsList() {
    wx.showLoading({
      title: '请稍后'
    })
    list({
      status: 'ANNOUNCED'
    }, (e) => {
      const alias = {};
      e.map(it => {
        alias[it.id] = it.name;
      })
      //  this.fetchRecipeById();
      this.fetchRecipeHistory();
      this.setData({
        list: e.sort((a, b) => {
          return a.name.localeCompare(b.name)
        }),
        ingredientsList: e,
        alias
      })
    })
  },
  fetchRecipeHistory() {
    fetchListHistory({
      recipeId: this.data.id
    }, (res => {
      wx.hideLoading();
      const candidateIndex = res.findIndex(it => it.candidate);
      if (candidateIndex>-1) {
        this.setData({
          __historyList: res,
          historyListLength: res.length,
          current: candidateIndex
        })
        this.recipeHandler(res[candidateIndex]);
      
      } else {
        recipeApi.recipeId(this.data.id, (result) => {
              this.setData({
                __historyList: [result, ...res],
                historyListLength: [result, ...res].length
              })
              this.recipeHandler(result);
        })
      }
    }))
  },
  onRefresh(event) {
    this.recipeHandler(event.detail);
    this.onSwipeClose();
  },
  /**
   * 查询所有配方
   */
  getAllRecipe() {
    recipeApi.recipeList({}, res => {
      const list = res.map(it => {
        return {
          text: it?.ingredients?.name,
          id: it?.ingredients?.id,
          number: it?.number
        }
      })
      this.setData({
        recipeListAll: list
      })
    })
  },
  selectHandler(event) {
    let arr = [...this.data.values];
    arr[event.currentTarget.dataset.index]['id'] = event.detail;
    this.setData({
      values: arr
    })
  },
  add(id, number) {
    this.setData({
      values: [...this.data.values, {
        id: id || '',
        number: number || ''
      }]
    })
  },
  numberChange(event) {

    const id = event.currentTarget.dataset.id;
    const arr = [...this.data.ingredientsList];
    const selectList = [...this.data.selectList];

    arr.forEach(it => {
      if (it.id === id) {
        it.number = event.detail;
      }
    })
    selectList.forEach(it => {
      if (it.value === id) {
        it.number = event.detail
      }
    })

    const total = this.getTotal(selectList);
    this.setData({
      ingredientsList: arr,
      selectList,
      total
    })
  },
  fetchRecipeById(id) {

    recipeApi.recipeId(id || this.data.id, (res) => {
      this.recipeHandler(res);
    })
  },
  recipeHandler(res) {
    const {
      name
    } = res;
    const list = [...this.data.list];
    const values = res.recipeCombination?.map(it => {
      return {
        id: it?.ingredients?.id,
        number: it?.number

      }
    })
    const total = this.getTotal(values);

    const ingredientsList = this.data.ingredientsList.map(it => {
      return {
        ...it,
        number: values.find(item => {
          return item.id === it.id
        })?.number || '0'
      }
    })
    const alias = {};
    const d = res.recipeCombination.map(it => {
      alias[it?.ingredients?.id] = it?.ingredients.name;
      return {
        text: it?.ingredients.name,
        value: it?.ingredients.id,
        number: it?.number
      }
    })

    const dropList = ingredientsList.map(it => {
      const valid = d.every(item => item.value !== it?.id);
      if (valid) {
        return {
          text: it?.name,
          value: it?.id,
          number: ''
        }
      }
      return false
    }).filter(it => it)
    const __historyListItem = this.data.__historyList[0];
    this.setData({
      values,
      name,
      dataSource: res,
      // factorSelect: [factorManageId],
      list,
      selectList: d,
      alias,
      ingredientsList,
      dropList,
      status: res.status,
      total,
      enableEdit: __historyListItem.status === undefined || __historyListItem.status === 'TO_BE_ANNOUNCED' || (this.data.root && __historyListItem.status === 'CHECK')
    })
    // wx.setNavigationBarTitle({
    //   title: name
    // })
  },
  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  onShowHistory(event) {
    const data = event.detail;
    this.setData({
      __historyList: data
    })
    this.onSwipeShow();
  },
  onSwipeShow() {
    this.setData({

      swipeShow: true
    })
  },
  onSwipeClose() {
    this.setData({
      swipeShow: false
    })
  },
  /**
   * @param {*} event 
   * @description 跳转到原料
   */
  toMaterial(event) {
    const id = event.currentTarget.dataset.value.value;
    wx.navigateTo({
      url: '../material/index?id=' + id,
    })
  },
  noop() {},
  /**
   * 刷新配方列表
   */
  async onRefreshRecipe() {
    this.setData({
      refreshLoading: true
    })
    await this.fetchIngredientsList();
    const selectList = [...this.data.selectList],
      dropList = [...this.data.dropList],
      list = dropList.filter(it => {
        return selectList.find(item => {
          return item.value === it.value
        }) === undefined
      });
    this.setData({
      dropList: list,
      refreshLoading: false
    })

  },
  /**
   * @param {Array} list 
   * @return Number
   */
  getTotal(list) {
    const total = list.reduce((preVal, currentVal) => {
      return preVal + Number(currentVal.number)
    }, 0).toFixed(2);
    return total;
  },
  /**
   * 删除item
   * @param {*} event 
   */
  delectItem(event) {
    const index = event.currentTarget.dataset.index;
    const dropList = [...this.data.dropList],
      checkboxValue = [...this.data.checkboxValue],
      selectList = [...this.data.selectList];
    selectList[index].number = '0';
    checkboxValue.unshift(selectList[index].value);
    dropList.unshift(selectList[index]);
    selectList.splice(index, 1);
    const total = this.getTotal(selectList);
    this.setData({
      dropList,
      selectList,
      total,
      checkboxValue
    })
  },
  //判断资料里是否存在0
  validRecipeCombinationHasZero(arr) {
    return arr.some(it => {
      return it.number && String(it.number) == "0"
    })
  },
  /**
   * 更新 或发布
   */
  update() {
    const hasCandidate = this.data.__historyList.some(it => {
      return it.candidate
    })
    if (hasCandidate) {
      wx.showModal({
        content: '此配方已有候选记录，此时更改配方数据可能会导致此配方与候选配方数据不一致，确定要修改吗？',
        success: res => {
          if (res.confirm) {
            const {
              name
            } = this.data;

            const recipeCombination = this.data.ingredientsList.filter(it => {
              return this.data.selectList.find(item => {
                return item.value === it.id
              }) !== undefined
            }).map(it => {
              return {
                ingredients: it,
                number: this.data.selectList.find(item => {
                  return item.value === it.id
                })?.number
              }
            })
            if (this.validRecipeCombinationHasZero(recipeCombination)) {
              wx.showModal({
                showCancel: false,
                content: "份额不可以为0"
              })
              return
            }
            //  const new_or_old = this.data.factorData.calciumOxide ? this.data.factorData : this.data.factorDataSource;

            // const recipeOperationData = this.data.dataSource?.recipeOperationData?.map(it => {
            //   return {
            //     ...it,
            //     ...new_or_old[it['elementType']]
            //   }
            // })
            // // 查看是否有膨胀因子
            // const correctionAmount = recipeOperationData.find(it => {
            //   return it.elementType === 'correctionAmount'
            // })
            // if (correctionAmount === undefined) {
            //   recipeOperationData.push({
            //     elementType: 'correctionAmount',
            //     expansionFactor: this.data.factorData['correctionAmount']['expansionFactor']
            //   })
            // }
            const numberSettings = this.selectComponent("#vc-number")?.getDataSource();

            const number_data = numberSettings.map(it => {
              return {
                name: it.name,
                numSelectManageId: it.numSelectManageId,
                remark: it.remark,
                sortNumber: it.sortNumber,
                value: it.value
              }
            })
            const data = {
              name,
              recipeCombination,
              productionNumberDatas: number_data,
              ...this.data._performanceData
            }
            let _d = Object.assign({}, this.data.dataSource, data);
            if (this.data.status === 'CHECK' && this.data.root) {
              _d.status = "ANNOUNCED";
            }
            recipeApi.recipeUpdate(_d, () => {
              // selectItem = d;
              wx.showModal({
                title: '提示',
                content: '已完成保存，是否返回上一层?',
                success: (res) => {
                  res.confirm && this.goBack(this.data.dataSource);
                }
              })
              if (_d.status === 'CHECK') {
                this.fetchRecipeById();
              }
            })
          }
        }
      })
    }
  },

  onDelectItems() {
    this.setData({
      dataSource: this.data.__historyList[0],
      __historyList: [this.data.__historyList[0]],
      current: 0

    })
    this.fetchRecipeHistory()
  },
  onDelectItemById() {
    removeById(this.data.dataSource, () => {
      wx.showModal({
        content: '确定要删除吗？',
        success: res => {
          if (res.confirm) {
            const __historyList = this.data.__historyList.filter(it => {
              return it.id !== this.data.dataSource.id || !it.recipeId
            })
            this.setData({
              dataSource: __historyList[0],
              __historyList,
              current: 0,
              historyListLength: __historyList.length
            })
            this.recipeHandler(__historyList[0])
          }
        }
      })
    })
  },
  onAdd(event) {

    const data = event.detail;
    this.setData({
      __historyList: data
    })
  },
  /**
   * 创建配方副本
   */
  create() {
    const {
      name,
      //factorSelect
    } = this.data;

    const recipeCombination = this.data.ingredientsList.filter(it => {
      return this.data.selectList.find(item => {
        return item.value === it.id
      }) !== undefined
    }).map(it => {
      return {
        ingredients: it,
        number: this.data.selectList.find(item => {
          return item.value === it.id
        })?.number
      }
    })
    if (this.validRecipeCombinationHasZero(recipeCombination)) {
      wx.showModal({
        showCancel: false,
        content: "份额不可以为0"
      })
      return
    }

    const newName = name + '-副本';
    wx.showModal({
      title: '填写配方副本名称',
      content: newName,
      editable: true,
      placeholderText: newName,
      success: async (res) => {
        if (res.confirm) {
          const numberSettings = this.selectComponent("#vc-number")?.getDataSource();

          const number_data = numberSettings.map(it => {
            return {
              name: it.name,
              numSelectManageId: it.numSelectManageId,
              remark: it.remark,
              sortNumber: it.sortNumber,
              value: it.value
            }
          })
          const data = {
            name: res.content || newName,
            recipeCombination,
            productionNumberDatas: number_data,
            ...this.data._performanceData,
            //    factorManageId: factorSelect[0],
            status: 'TO_BE_ANNOUNCED'
          }
          this.setData({
            preData: data
          })
          // if (this.data.recordId) {
          //   //如果没有釉料环节，那也就不必确认之前的步骤了
          //   const hasGlaze = await isDone(this.data.recordId, 'glazeId');
          //   if (!hasGlaze) {
          //     this.editHandler();
          //     return
          //   }
          //   const c = await this.asyncValid();
          //   if (!c) {
          //     this.onConfirmShow();
          //     return
          //   }
          // }
          this.editHandler();
        }
      }
    })
  },
  async asyncValid() {
    return new Promise((resolve, reject) => {
      _get(this.data.recordId, (res) => {
        const data = this.data.confirmList.map(it => {
          return {
            ...it,
            state: res[it['key']] !== null && res[it['key']] > 0
          }
        })
        this.setData({
          confirmList: data
        })
        //只要有一个流程无保存状态，弹框验证就不通过
        const validResult = data.every(it => it.state === false);
        resolve(validResult);
      }, reject)
    })
  },
  editHandler() {
    const _this = this,
      _data = this.data.preData;
    recipeApi.recipeAdd(_data, (e) => {
      selectItem = e;
      wx.showModal({
        title: '提示',
        content: '已完成保存，是否返回上一层?',
        success: (res) => {
          // res.confirm && _this.goBack(e);
          _this.goBack(e)
        }
      })
    })
  },
  onConfirmHide(valid) {
    this.setData({
      confirmShow: false
    })
    if (valid.detail) {
      this.editHandler();
    }
  },
  onConfirmShow() {
    this.setData({
      confirmShow: true
    })
  },
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  },
  setDisbale(id) {

    _get(id, res => {

      this.setData({
        enable: res.status === 0
      })
    })
  },
  /**
   * 设置配方列表下拉框
   */
  fetchFactorList() {
    factorApi.getFactor({}, res => {
      const list = res.map(it => {
        return {
          name: it.name,
          value: it.id
        }
      })
      this.setData({
        factorList: list
      })
    })
  },
  onRecipeChange(event) {

  },
  onNavChange(event) {
    this.recipeHandler(event.detail);
  },
  onPerformanceInputChange(event) {
    const {
      name,
      value
    } = event.detail;
    const _performanceData = this.data._performanceData;
    _performanceData[name] = value;
    this.setData({
      _performanceData
    })
  },
  useThis(event) {
    const index = event.currentTarget.dataset.index;
    const _dataSource = this.data.dataSource;
    wx.showModal({
      title: "提示",
      content: `确定要应用此数据吗？`,
      success: res => {
        if (res.confirm) {
          candidate({
            ..._dataSource,
            candidate: true
          }, () => {
            const __historyList = this.data.__historyList.map((it, i) => {
              return {
                ...it,
                candidate: i === index
              }
            });
            recipeApi.recipeUpdate({
              ..._dataSource,
              id: _dataSource.recipeId
            }, () => {
              __historyList[0] = {
                ..._dataSource,
                id: _dataSource.recipeId,
                name: __historyList[0]?.['name']
              }
              this.setData({
                __historyList,
                dataSource: __historyList[index],
              })
            })
          })
        }
      }
    })
  },
  toggleCompositionPopup() {
    this.setData({
      compositionShow: !this.data.compositionShow
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setPage(options.id, options.param);
    this.fetchIngredientsList();
    //this.fetchFactorList();
    if (options.param) {
      this.setDisbale(options.param);
    }
    // this.getAllRecipe();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */

  onShow: function () {
    // const urls = ['pages/glaze/index'];
    // wx.onAppRoute((res) => {
    //   const pages = getCurrentPages();

    //   if (urls.includes(res.path) && selectItem && this.data.pages) {
    //     const prevPage = pages[pages.length - 1];
    //     //重新计算性能数据
    //     prevPage?.fetchRecipeList && prevPage?.fetchRecipeList(() => {

    //       prevPage.setData({
    //         selectItem
    //       })
    //     });
    //   } else if (selectItem && this.data.pages) {
    //     const lastPage = pages[pages.length - 2];
    //     lastPage?.fetchRecipeList && lastPage?.fetchRecipeList(() => {
    //       prevPage.setData({
    //         selectItem
    //       })
    //     });
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    setTimeout(() => {
      this.setData({
        pages: null
      })
    }, 1000)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})